package utils
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.ProgressEvent;
	import flash.utils.getTimer;
	import flash.utils.setTimeout;
	
	import types.Frame;
	import types.FrameAction;
	import types.ProfilingSession;
	import types.SubProvider;
	
	[Event(name="progress", type="flash.events.ProgressEvent")]
	[Event(name="complete", type="flash.events.Event")]
	public class SearchPOI extends EventDispatcher
	{
		private var _provider : ProfilingSession;		
		private var _searchId : Array;
		private var _targetedDataProvider : SubProvider;
		
		public function SearchPOI(provider : ProfilingSession, searchId : Array, targetedDataProvider : SubProvider)
		{
			super(null);
			_provider = provider;
			_searchId = searchId;
			_targetedDataProvider = targetedDataProvider;
			setTimeout(searchPOIStep, 10);
		}
		
		private function searchPOIStep(startIndex : uint = 0) : void
		{
			var timeLeft : int = 1000 / StageShare.stage.frameRate;
			var i : uint = startIndex;
			for(; i < _provider.frames.length && timeLeft > 0; ++i)
			{
				var ts : uint = getTimer();
				var frame : Frame = _provider.frames[i] as Frame;
				for each(var action : FrameAction in frame.children)
				{
					for each(var searchPattern : String in _searchId)
					if(action.name.indexOf(searchPattern) == 0)
						_targetedDataProvider.addValue({name: action.name}, action.start);
				}
				timeLeft -= getTimer() - ts;
			}
			
			dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS, false, false, i, _provider.frames.length));
				
			if(i < _provider.frames.length)
				setTimeout(searchPOIStep, 1, i);
			else
				dispatchEvent(new Event(Event.COMPLETE));
		}
	}
}